package org.dromara.shopping.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.QRCodeUtilEx;
import org.dromara.common.core.utils.file.FileUploadUtils;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.shopping.domain.ProductImg;
import org.dromara.shopping.domain.ProductOrder;
import org.dromara.shopping.service.IProductImgService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.shopping.domain.Product;
import org.dromara.shopping.service.IProductService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 商品
 *
 * @author Mr.Zhou
 * @date 2024-10-21
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/shopping/product")
public class ProductController extends BaseController {

    private final IProductService productService;
    private final IProductImgService productImgService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 查询商品列表
     */
    @SaCheckPermission("shopping:product:list")
    @GetMapping("/list")
    public TableDataInfo<Product> list(Product product, PageQuery pageQuery) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser.getRoleKey().equals("organ")){
            qw.eq("organ_id", loginUser.getOrganId());
        }

        TableDataInfo<Product> td = PageUtils.buildDataInfo(productService.page(PageUtils.buildPage(),qw));
        List<Product> list = td.getRows();
        return td;
    }

    /**
     * 导出商品列表
     */
    @SaCheckPermission("shopping:product:export")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(Product product, HttpServletResponse response) {
        List<Product> list = productService.list();
        ExcelUtil.exportExcel(list, "商品", Product.class, response);
    }

    /**
     * 获取商品详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("shopping:product:query")
    @GetMapping("/{id}")
    public R<Product> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        Product product = productService.goodsDetail(id);
        if(product!=null){

            QueryWrapper<ProductImg> qwImg = new QueryWrapper<>();
            qwImg.eq("product_id",product.getId());
            qwImg.eq("img_type",0);
            List<ProductImg> images = productImgService.list(qwImg);
            for (ProductImg img : images){
                if(StrUtil.isNotEmpty(img.getImgUrl())){
                    img.setImgUrlPath(imgUrl + img.getImgUrl());
                }
            }
            product.setProductImgs(images);


            String lunboImgs = "";
            QueryWrapper<ProductImg> qwLunbo = new QueryWrapper<>();
            qwLunbo.eq("product_id",product.getId());
            qwLunbo.eq("img_type",1);
            List<ProductImg> lunbos = productImgService.list(qwLunbo);
            for (ProductImg img : lunbos){
                if(StrUtil.isNotEmpty(img.getImgUrl())) {
                    lunboImgs += imgUrl + img.getImgUrl() + ",";
                    img.setImgUrlPath(imgUrl + img.getImgUrl());
                }
            }
            product.setProductImgLunbos(lunbos);

            if(StrUtil.isNotEmpty(lunboImgs)){
                lunboImgs = lunboImgs.substring(0,lunboImgs.length() - 1);
            }

            product.setSliderImagePath(lunboImgs);
        }
        return R.ok(product);
    }



    /**
     * 重置二维码
     */
    @Log(title = "重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @SaCheckPermission("shopping:product:edit")
    public R<Void> resetQrCode(@RequestBody Product product) {
        if(product.getId()!=null){
            try{
                product = productService.getById(product.getId());
                if(product != null){
                    if(StrUtil.isEmpty(product.getProductNo())){
                        String no = String.valueOf(2200000 + product.getId());
                        product.setProductNo(no);
                    }

                    String qrCode = "";
                    String fileName = "product_qr_" + product.getId() + ".jpg";
                    String content = "https://www.sdyuedou.com/wxmini/produ/detail?id=" + product.getId();
                    int upload_type = FileUploadUtils.TYPE_PRODUCT_QRCODE;
                    System.out.println("content:  "+ content);
                    String img_key = "";
                    img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, "No." + product.getProductNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                    qrCode = img_key;
                    product.setQrCode(qrCode);
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (productService.updateById(product)) {
                return R.ok();
            }
        }
        return R.fail();
    }

    @Log(title = "生成属性")
    @PostMapping(value = "/isFormatAttr/{id}/{isReset}")
    public R<Map<String, Object>> isFormatAttr(@PathVariable("id") Long id, @PathVariable("isReset") Integer isReset, @RequestBody String jsonStr){
        return R.ok(productService.getFormatAttr(id,jsonStr,false,isReset));
    }


    /**
     * 修改售罄状态
     */
    @SaCheckPermission("shopping:product:edit")
    @Log(title = "修改售罄状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeSaleOutStatus")
    public R changeSaleOutStatus(@RequestBody Product product) {
        return toAjax(productService.updateById(product));
    }


    /**
     * 新增商品
     */
    @SaCheckPermission("shopping:product:add")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody Product product) {
        int ret = 0;
        try{
            product.setCreateTime(new Date());
            LoginUser loginUser = LoginHelper.getLoginUser();
            if(loginUser.getRoleKey().equals("organ")){
                product.setOrganId(loginUser.getOrganId());
            }

            ret = productService.addProduct(product);
            if(ret == -1){
                return R.fail("请上传轮播图");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return toAjax(ret);
    }

    /**
     * 修改商品
     */
    @SaCheckPermission("shopping:product:edit")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Product product) {
        int ret = 0;
        try{
            ret = productService.addProduct(product);

            if(ret == -1){
                return R.fail("请上传轮播图");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return toAjax(ret);
    }


    /**
     * 修改商品
     */
    @SaCheckPermission("shopping:product:edit")
    @Log(title = "修改商品", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping("/num")
    public R<Void> num(@Validated(EditGroup.class) @RequestBody Product product) {
        return toAjax(productService.updateById(product) ? 1 : 0);
    }



    @Log(title ="查询商品列表")
    @GetMapping("/showList")
    public List<Product> showList(@Validated Product product) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(product.getMerId())){
            qw.eq("mer_id",product.getMerId());
        }
        if (ObjectUtil.isNotEmpty(product.getCateId())){
            qw.eq("cate_id",product.getCateId());
        }
        TableDataInfo<Product> td = PageUtils.buildDataInfo(productService.page(PageUtils.buildPage(),qw));
        List<Product> list = td.getRows();
        for (Product list1:list){
            list1.setImage(imgUrl+list1.getImage());
        }
        return list;
    }

    /**
     * 删除商品
     *
     * @param ids 主键串
     */
    @SaCheckPermission("shopping:product:remove")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(productService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
